package com.strongbj.iot.devices.hr.request.handle;

import java.net.InetSocketAddress;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.hr.message.HRMessageFactory;
import com.strongbj.iot.devices.hr.message.MQMessageOfHR;
import com.strongbj.iot.devices.hr.response.handle.HRResponseHandleContext;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.group.ChannelMatcher;

/**
 * 控制蜂鸣器发声处理类
 * 
 * @author Pingfan
 *
 */
public class HRControlBuzzerSoundHandle implements IMessageHandle<MQMessageOfHR, Object> {
	private static Logger logger = LogManager.getLogger(BuzzerHandle.class.getName());
	private final static String ACTION_CODE = "collect015";
	private HRMessageFactory hrMessageFactory = new HRMessageFactory();
	
	@Override
	public boolean isHandle(MQMessageOfHR t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfHR t) {
		// 取门禁ip
		JSONObject jsonObject = (JSONObject) JSON.toJSON(t.getAwsPostdata());
		String ip = jsonObject.getString("devIp");
		// 拼接数据段
		byte soundLength = jsonObject.getByte("soundLength"); // 声音长度
		byte pauseTime = jsonObject.getByte("pauseTime");  // 停顿时间
		byte repeatNumber = jsonObject.getByte("repeatNumber");  // 重复次数
		byte[] data = {soundLength, pauseTime, repeatNumber};  
		// 发送控制蜂鸣器发声指令到门禁
		byte[] controlBuzzerSoundCommand = hrMessageFactory.createHRMessage((byte) 0x0F, (byte) 0x00, (byte) 0x00, data);
		ByteBuf bs = Unpooled.copiedBuffer(controlBuzzerSoundCommand);
		HRResponseHandleContext.channels.writeAndFlush(bs, new MyChannelMatchers(ip));
		logger.info("向HR设备发送【控制蜂鸣器发声】成功, ip={}, 数据={}", ip, ByteUtil.byteArrToHexString(controlBuzzerSoundCommand, true));
		return null;
	}
	
	class MyChannelMatchers implements ChannelMatcher {
		private String currentIP;

		public MyChannelMatchers(String ip) {
			this.currentIP = ip;
		}

		@Override
		public boolean matches(Channel channel) {
			InetSocketAddress insocket = (InetSocketAddress) channel.remoteAddress();
			if (insocket.getAddress().getHostAddress().equals(this.currentIP)) {
				return true;
			} else {
				return false;
			}
		}
	}
}
